import re
import sys

def parse_process_info(file_path):
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()

        processes = {}
        header_found = False

        for line in lines:
            # Skip lines that start with "Mem", "CPU", or "Load average"
            if line.startswith(("Mem", "CPU", "Load average")):
                continue

            # Check for the header line that indicates the start of process information
            if re.match(r'^\s*PID\s+PPID\s+USER\s+STAT', line):
                header_found = True
                continue  # Skip the header line

            # Skip lines before header
            if not header_found:
                continue

            # Process the process information lines
            line = re.sub(r'(\d+)m(\d+)', r'\1m \2', line)  # Handle memory and percent concatenation
            parts = re.split(r'\s+', line.strip())

            # Check if we have at least 8 columns
            if len(parts) >= 8:
                # Extract PID, USER, and COMMAND
                pid = parts[0]
                user = parts[2]
                command = ' '.join(parts[8:])  # Join everything after the first 8 columns
                
                # Extract CPU percentage (7th column)
                try:
                    cpu_percentage = float(parts[7]) if len(parts) > 7 and parts[7].replace('.', '', 1).isdigit() else 0.0
                except ValueError:
                    continue

                # Store in dictionary if user is 'root'
                if user == 'root':
                    if pid not in processes:
                        processes[pid] = {
                            'USER': user,
                            'COMMAND': command,
                            'CPU': []
                        }
                    processes[pid]['CPU'].append(cpu_percentage)

        # Calculate average CPU for each process and filter results
        filtered_processes = {}
        for pid, info in processes.items():
            average_cpu = sum(info['CPU']) / len(info['CPU']) if info['CPU'] else 0
            if average_cpu > 0.5:
                filtered_processes[pid] = {
                    'USER': info['USER'],
                    'COMMAND': info['COMMAND'],
                    'AVERAGE_CPU': average_cpu
                }

        return filtered_processes
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return {}
    except Exception as e:
        print(f"An error occurred: {e}")
        return {}

def main():
    # Check if a file path was provided as a command line argument
    if len(sys.argv) < 2:
        print("Usage: python script.py <file_path>")
        return

    file_path = sys.argv[1]
    process_info = parse_process_info(file_path)

    # Sort processes by average CPU in descending order and print the results
    sorted_processes = sorted(process_info.items(), key=lambda x: x[1]['AVERAGE_CPU'], reverse=True)

    for pid, info in sorted_processes:
        print(f"PID: {pid}, USER: {info['USER']}, COMMAND: {info['COMMAND']}, AVERAGE CPU: {info['AVERAGE_CPU']:.2f}")

if __name__ == "__main__":
    main()
